Skip to content

Instantly share code, notes, and snippets.

@hjdo hjdo/main.go
Last active Nov 6, 2018

Embed
What would you like to do?
Go HTTP接口简单例子
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type UserInfo struct {
Email string `json:"email"`
Password string `json:"password"`
}
func main() {
http.HandleFunc("/api/login", loginFunc)
http.HandleFunc("/api/get", getUserInfo)
http.HandleFunc("/", index)
log.Fatal("启动服务失败:", http.ListenAndServe(":2333", nil))
}
func loginFunc(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
decoder := json.NewDecoder(r.Body)
res := false
reqData := UserInfo{}
decoder.Decode(&reqData)
if reqData.Email != "" && reqData.Password != "" {
res = true
}
fmt.Fprintf(w, "%v", res)
}
func getUserInfo(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
resData := UserInfo{"123@qq.com", "123123"}
j, _ := json.Marshal(resData)
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
func index(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
fmt.Fprintf(w, "Hello golang http!")
}
// 允许跨域请求
func setupResponse(w *http.ResponseWriter, r *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.