平时写一些小工具的时候,经常要百度找一些相关的代码,其实不是很复杂的代码,就是一时想不起来怎么写。所以准备将一些 Go 代码片段收集一下,以便于在以后的开发过程中参考。
-
Web服务(可用于开发代理工具)
package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { // 监听端口 port := ":9527" msg := fmt.Sprintf("服务运行中... 端口[%v]", port) log.Printf(msg) // 监听服务 // TODO 需要确认端口是否被占用 http.ListenAndServe(port, http.HandlerFunc(Handler)) } // Handler 响应函数 func Handler(w http.ResponseWriter, r *http.Request) { log.Printf("%+v", *r) s:= "Hello, world." // 转换成字节 stream, err := json.Marshal(s) if err != nil { log.Println(err) } w.Write(stream) } -
简易 Web 服务,返回 json 。
package http import ( "encoding/json" "fmt" "log" "net/http" ) type Hello struct { Code string `json:"code"` Message string `json:"message"` } func RunHttp() { // 监听端口 port := ":9527" msg := fmt.Sprintf("服务运行中... 端口[%v]", port) log.Printf(msg) // 监听服务 // TODO 需要确认端口是否被占用 http.ListenAndServe(port, http.HandlerFunc(Handler)) } // Handler 响应函数 func Handler(w http.ResponseWriter, r *http.Request) { //log.Printf("%+v", *r) helloWorld := Hello{ Code: "12", Message: "hello world", } // 转换成字节 stream, err := json.Marshal(&helloWorld) if err != nil { log.Println(err) log.Println("ERROR: json.Marshal(&helloWorld)") } //log.Println(stream) w.Header().Set("Content-Type", "application/json") w.Write(stream) } -
struct的成员同时支持yaml和json
type HelloWorld struct { Hello string `yaml:"hello" json:"hello"` World string `yaml:"world" json:"world"` }