file_server.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package file_server_sdk
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. )
  11. var (
  12. persistent = "api/v1/files/persistent" //文件持久化路径
  13. )
  14. type persistentStruct struct {
  15. Hash string `json:"hash"`
  16. }
  17. type Config struct {
  18. Host string
  19. }
  20. type ConfigHandle struct {
  21. Host string
  22. }
  23. var (
  24. once sync.Once
  25. internalHandle *ConfigHandle
  26. )
  27. func (c *Config) Init() {
  28. //代码运行中需要的时候执行,且只执行一次
  29. once.Do(func() {
  30. internalHandle = &ConfigHandle{
  31. Host: c.Host,
  32. }
  33. })
  34. }
  35. // GetHandle get handle
  36. func GetHandle() *ConfigHandle {
  37. return internalHandle
  38. }
  39. //HandlePersistent 设置文件持久化
  40. func (c *ConfigHandle) HandlePersistent(hash string) error {
  41. if hash == "" {
  42. return errors.New("缺少请求参数")
  43. }
  44. param := persistentStruct{
  45. Hash: hash,
  46. }
  47. s, err := json.Marshal(param)
  48. if err != nil {
  49. return err
  50. }
  51. url := fmt.Sprintf("%s/%s", c.Host, persistent)
  52. reqBody := strings.NewReader(string(s))
  53. req, err := http.NewRequest(http.MethodPut, url, reqBody)
  54. if err != nil {
  55. return err
  56. }
  57. req.Header.Set("Content-type", "application/json")
  58. client := &http.Client{}
  59. response, err := client.Do(req)
  60. if err != nil {
  61. return err
  62. }
  63. _, err = ioutil.ReadAll(response.Body)
  64. if err != nil {
  65. return err
  66. }
  67. return nil
  68. }