resource.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package resource
  2. import (
  3. "net/http"
  4. )
  5. type Resource struct {
  6. Path string
  7. Ctype string
  8. Bytes []byte
  9. }
  10. type resource struct {
  11. maxurl int
  12. list map[string]Resource
  13. }
  14. func New() *resource {
  15. r := resource{maxurl: 0}
  16. r.list = map[string]Resource{}
  17. return &r
  18. }
  19. func (this *resource) Add(path string, ctype string, bytes []byte) {
  20. // Do not add if already in resources list
  21. if _, ok := this.list[path]; ok == true {
  22. return
  23. }
  24. // Add to resources list
  25. this.maxurl = len(path)
  26. this.list[path] = Resource{
  27. Path: path,
  28. Ctype: ctype,
  29. Bytes: bytes,
  30. }
  31. }
  32. func (this *resource) Response(w http.ResponseWriter, r *http.Request, before func(w http.ResponseWriter, r *http.Request, i *Resource), after func(w http.ResponseWriter, r *http.Request, i *Resource)) bool {
  33. // Do not process if this is not necessary
  34. if len(r.URL.Path) <= 1 || len(r.URL.Path)-1 > this.maxurl {
  35. return false
  36. }
  37. // Check for resource
  38. res, ok := this.list[r.URL.Path[1:]]
  39. if ok == false {
  40. return false
  41. }
  42. // Call `before` callback
  43. if before != nil {
  44. before(w, r, &res)
  45. }
  46. // Send resource
  47. w.Header().Set("Content-Type", res.Ctype)
  48. w.Write(res.Bytes)
  49. // Call `after` callback
  50. if after != nil {
  51. after(w, r, &res)
  52. }
  53. return true
  54. }