github.com/searKing/golang/go@v1.2.117/net/restful/server.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package restful
     6  
     7  import (
     8  	"encoding/json"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  func HttpGetHandler(v any, w http.ResponseWriter, r *http.Request) {
    16  	body, err := json.MarshalIndent(v, "", "  ")
    17  	if err != nil {
    18  		body = []byte("[]")
    19  	}
    20  
    21  	// response
    22  	w.Header().Set("Content-Type", "application/json")
    23  	w.Header().Set("Content-Length", strconv.FormatInt(int64(len(body)), 10))
    24  	w.Header().Set("Connection", "close")
    25  	w.WriteHeader(http.StatusOK)
    26  	w.Write(body)
    27  }
    28  
    29  func HttpPostHandler(v any, w http.ResponseWriter, r *http.Request) (finished bool) {
    30  	if r.Method == http.MethodPost {
    31  		r.ParseForm()
    32  		if r.ContentLength == -1 {
    33  			http.NotFound(w, r)
    34  			return true
    35  		} else {
    36  			ctype := strings.ToLower(r.Header.Get("Content-Type"))
    37  			if ctype != "application/json" {
    38  				http.NotFound(w, r)
    39  				return true
    40  			}
    41  
    42  			body, err := ioutil.ReadAll(r.Body)
    43  			if err != nil {
    44  				http.Error(w, err.Error(), http.StatusBadRequest)
    45  				return true
    46  			}
    47  
    48  			err = json.Unmarshal(body, v)
    49  			if err != nil {
    50  				http.Error(w, err.Error(), http.StatusBadRequest)
    51  				http.NotFound(w, r)
    52  				return true
    53  			}
    54  			return false
    55  		}
    56  	} else {
    57  		http.NotFound(w, r)
    58  		return true
    59  	}
    60  }