github.com/l3x/learn-fp-go@v0.0.0-20171228022418-7639825d0b71/3-functional-techniques/ch07-func-param/01_func_param/src/utils/utils.go (about)

     1  package utils
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"os"
     9  	"path"
    10  	"runtime"
    11  	"strings"
    12  )
    13  
    14  type APIError struct {
    15  	ErrorMessage string `json:"error_message"`
    16  	HTTPStatus   int    `json:"http_status"`
    17  }
    18  
    19  type HttpErrorHandler struct {
    20  	Caller   string
    21  	Response http.ResponseWriter
    22  	Request  *http.Request
    23  }
    24  
    25  const (
    26  	ErrorActionErr = iota
    27  	ErrorActionWarn
    28  	ErrorActionDebug
    29  	ErrorActionInfo
    30  )
    31  
    32  func NewHttpErrorHandle(caller string, response http.ResponseWriter, request *http.Request) *HttpErrorHandler {
    33  	return &HttpErrorHandler{caller, response, request}
    34  }
    35  
    36  func (h *HttpErrorHandler) Handle(err error, httpStatus int, action int) bool {
    37  	if err != nil {
    38  		_, filepath, line, _ := runtime.Caller(1)
    39  		_, file := path.Split(filepath)
    40  		Error.Printf("HttpErrorHandler()->[file:%s line:%d]: %s", file, line, err.Error())
    41  		apiErr := &APIError{
    42  			ErrorMessage: err.Error(),
    43  			HTTPStatus:   httpStatus,
    44  		}
    45  		serialErr, _ := json.Marshal(&apiErr)
    46  		h.Response.Header().Set("Content-Type", "application/json")
    47  		h.Response.WriteHeader(httpStatus)
    48  		io.WriteString(h.Response, string(serialErr))
    49  	}
    50  	return err != nil
    51  }
    52  
    53  func FromLineOfFile() string {
    54  		_, filepath, line, _ := runtime.Caller(1)
    55  		_, file := path.Split(filepath)
    56  		return fmt.Sprintf("[file:%s line:%d]", file, line)
    57  }
    58  
    59  func HandlePanic(err error) {
    60  	if err != nil {
    61  		_, filePath, lineNo, _ := runtime.Caller(1)
    62  		_, fileName := path.Split(filePath)
    63  		msg := fmt.Sprintf("[file:%s line:%d]: %s", fileName, lineNo, err.Error())
    64  		panic(msg)
    65  	}
    66  }
    67  
    68  func HandleError(err error, action int) bool {
    69  	if err != nil {
    70  		_, filepath, line, _ := runtime.Caller(1)
    71  		_, file := path.Split(filepath)
    72  		switch action {
    73  		case ErrorActionErr:
    74  			Error.Printf("[file:%s line:%d]: %s", file, line, err.Error())
    75  			break
    76  		case ErrorActionWarn:
    77  			Error.Printf("[file:%s line:%d]: %s", file, line, err.Error())
    78  			break
    79  		case ErrorActionDebug:
    80  			Error.Printf("[file:%s line:%d]: %s", file, line, err.Error())
    81  			break
    82  		case ErrorActionInfo:
    83  			Error.Printf("[file:%s line:%d]: %s", file, line, err.Error())
    84  			break
    85  		}
    86  	}
    87  	return err != nil
    88  }
    89  
    90  func WriteFile(filename string, source io.Reader) error {
    91  	writer, err := os.Create(filename)
    92  	if err != nil {
    93  		return err
    94  	}
    95  	defer writer.Close()
    96  	io.Copy(writer, source)
    97  	return nil
    98  }
    99  
   100  func PadRight(str string, padWith string, length int) string {
   101  	count := length - len(str)
   102  	if count < 0 {
   103  		count = 0
   104  	}
   105  	return str + strings.Repeat(padWith, count)
   106  }
   107  
   108  func InSlice(slice []string, searchFor string) (found bool) {
   109  	for _, v := range slice {
   110  		if searchFor == v {
   111  			found = true
   112  		}
   113  	}
   114  	return found
   115  }