Usually write some small tools, often baidu to find some relevant code, in fact, is not very complex code, just can’t remember how to write. So get ready to collect some Go code snippets for reference in future development.

  1. Web services (can be used to develop proxy tools)

    package main
    
     import (
             "encoding/json"
             "fmt"
             "log"
             "net/http"
     )
    
     func main(a) {
             // Listen on the port
             port := ": 9527"
             msg := fmt.Sprintf("Service running... Port [v] %", port)
             log.Printf(msg)
    
             // Listen to the service
             // TODO needs to verify that the port is occupied
             http.ListenAndServe(port, http.HandlerFunc(Handler))
     }
    
     // Handler responds to the function
     func Handler(w http.ResponseWriter, r *http.Request) {
             log.Printf("%+v", *r)
    
             s:= "Hello, world."
             // Convert to bytes
             stream, err := json.Marshal(s)
             iferr ! =nil {
                     log.Println(err)
             }
    
             w.Write(stream)
     }
    Copy the code
  2. Struct members support both YAML and JSON

    type HelloWorld struct {
     Hello string `yaml:"hello" json:"hello"`
     World string `yaml:"world" json:"world"`
    }
    Copy the code