- 能够在环境中设置代理goproxy.cn防止国内下包出错
启动服务
最开始能够先对一个端口18080启动一个服务:
package mainimport ( "log" "net/http")func index(w http.ResponseWriter, r *http.Request) {}func main() { // 启动一个http服务 指明ip和端口 server := http.Server{ Addr: "127.0.0.1:18080", } //响应拜访http://localhost:18080/的申请 http.HandleFunc("/", index) // 监听对应的端口 & 启动服务 if err := server.ListenAndServe(); err != nil { log.Println(err) }}
成果:
没有404,阐明服务启动胜利。
增加响应
接下来,咱们在index这个func能够增加响应:
func index(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hey this is LiberHom"))}
传递json数据
当然,理论开发个别不会是这么简略的文字,而是一些web页面,须要给前端返回json信息,咱们须要在Header中指明是json。
func index(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte("hey this is LiberHom"))}
成果:
咱们能够结构残缺一些的例子如下:
package mainimport ( "encoding/json" "log" "net/http")//结构一些数据type IndexData struct { Title string `json:"title"` Desc string `json:"desc"`}func index(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var indexData IndexData indexData.Title = "Liber-Blog" indexData.Desc = "this is the desc part" //把构造体实例转成对应的json jsonStr, _ := json.Marshal(indexData) w.Write(jsonStr)}func main() { // 启动一个http服务 指明ip和端口 server := http.Server{ Addr: "127.0.0.1:18080", } //响应拜访http://localhost:18080/的申请 http.HandleFunc("/", index) // 监听对应的端口 & 启动服务 if err := server.ListenAndServe(); err != nil { log.Println(err) }}
运行后果如下:
参考: bilibili