pushstate.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package web
  2. import (
  3. "encoding/json"
  4. "net/url"
  5. )
  6. func Location(query url.Values) (r *LocationBuilder) {
  7. r = &LocationBuilder{
  8. MyQuery: make(map[string]json.Marshaler),
  9. }
  10. r.Query(query)
  11. return
  12. }
  13. func (b *LocationBuilder) URL(url string) (r *LocationBuilder) {
  14. b.MyURL = url
  15. return b
  16. }
  17. func (b *LocationBuilder) MergeQuery(v bool) (r *LocationBuilder) {
  18. b.MyMergeQuery = v
  19. return b
  20. }
  21. func (b *LocationBuilder) MergeWithAppend(key string, values []string) (r *LocationBuilder) {
  22. b.MergeQuery(true)
  23. b.MyQuery[key] = valueOp{
  24. Values: values,
  25. Add: true,
  26. }
  27. return b
  28. }
  29. func (b *LocationBuilder) MergeWithRemove(key string, values []string) (r *LocationBuilder) {
  30. b.MergeQuery(true)
  31. b.MyQuery[key] = valueOp{
  32. Values: values,
  33. Remove: true,
  34. }
  35. return b
  36. }
  37. func (b *LocationBuilder) Query(query url.Values) (r *LocationBuilder) {
  38. for k, vs := range query {
  39. b.PutQuery(k, vs)
  40. }
  41. return b
  42. }
  43. func (b *LocationBuilder) PutQuery(key string, values []string) (r *LocationBuilder) {
  44. b.MyQuery[key] = valuesMarshaller(values)
  45. return b
  46. }
  47. func (b *LocationBuilder) StringQuery(v string) (r *LocationBuilder) {
  48. b.MyStringQuery = v
  49. return b
  50. }
  51. func (b *LocationBuilder) ClearMergeQuery(clearKeys []string) (r *LocationBuilder) {
  52. b.MyClearMergeQueryKeys = clearKeys
  53. return b
  54. }
  55. type valuesMarshaller []string
  56. func (vm valuesMarshaller) MarshalJSON() ([]byte, error) {
  57. return json.Marshal([]string(vm))
  58. }
  59. // LocationBuilder mapping to type.ts Location interface
  60. type LocationBuilder struct {
  61. MyMergeQuery bool `json:"mergeQuery,omitempty"`
  62. MyURL string `json:"url,omitempty"`
  63. MyStringQuery string `json:"stringQuery,omitempty"`
  64. MyClearMergeQueryKeys []string `json:"clearMergeQueryKeys,omitempty"`
  65. MyQuery map[string]json.Marshaler `json:"query,omitempty"`
  66. }
  67. type valueOp struct {
  68. Values []string `json:"values,omitempty"`
  69. Add bool `json:"add,omitempty"`
  70. Remove bool `json:"remove,omitempty"`
  71. }
  72. func (vm valueOp) MarshalJSON() ([]byte, error) {
  73. return json.Marshal(vm)
  74. }