1 module hunt.http.codec.http.model.CookieGenerator; 2 3 import hunt.http.codec.http.model.Cookie; 4 5 import hunt.container.List; 6 7 import hunt.lang.exception; 8 import hunt.string; 9 10 import std.array; 11 12 // import hunt.http.utils.VerifyUtils; 13 14 abstract class CookieGenerator { 15 16 static string generateCookies(List!Cookie cookies) { 17 if (cookies is null) { 18 throw new IllegalArgumentException("the cookie list is null"); 19 } 20 21 if (cookies.size() == 1) { 22 return generateCookie(cookies.get(0)); 23 } else if (cookies.size() > 1) { 24 StringBuilder sb = new StringBuilder(); 25 26 sb.append(generateCookie(cookies.get(0))); 27 for (int i = 1; i < cookies.size(); i++) { 28 sb.append(';').append(generateCookie(cookies.get(i))); 29 } 30 31 return sb.toString(); 32 } else { 33 throw new IllegalArgumentException("the cookie list size is 0"); 34 } 35 } 36 37 static string generateCookie(Cookie cookie) { 38 if (cookie is null) { 39 throw new IllegalArgumentException("the cookie is null"); 40 } else { 41 return cookie.getName() ~ "=" ~ cookie.getValue(); 42 } 43 } 44 45 static string generateSetCookie(Cookie cookie) { 46 if (cookie is null) { 47 throw new IllegalArgumentException("the cookie is null"); 48 } else { 49 StringBuilder sb = new StringBuilder(); 50 51 sb.append(cookie.getName()).append('=').append(cookie.getValue()); 52 53 if (!empty(cookie.getComment())) { 54 sb.append(";Comment=").append(cookie.getComment()); 55 } 56 57 if (!empty(cookie.getDomain())) { 58 sb.append(";Domain=").append(cookie.getDomain()); 59 } 60 if (cookie.getMaxAge() >= 0) { 61 sb.append(";Max-Age=").append(cookie.getMaxAge()); 62 } 63 64 string path = empty(cookie.getPath()) ? "/" : cookie.getPath(); 65 sb.append(";Path=").append(path); 66 67 if (cookie.getSecure()) { 68 sb.append(";Secure"); 69 } 70 71 sb.append(";Version=").append(cookie.getVersion()); 72 73 return sb.toString(); 74 } 75 } 76 77 // static string generateServletSetCookie(javax.servlet.http.Cookie cookie) { 78 // if (cookie == null) { 79 // throw new IllegalArgumentException("the cookie is null"); 80 // } else { 81 // StringBuilder sb = new StringBuilder(); 82 83 // sb.append(cookie.getName()).append('=').append(cookie.getValue()); 84 85 // if (VerifyUtils.isNotEmpty(cookie.getComment())) { 86 // sb.append(";Comment=").append(cookie.getComment()); 87 // } 88 89 // if (VerifyUtils.isNotEmpty(cookie.getDomain())) { 90 // sb.append(";Domain=").append(cookie.getDomain()); 91 // } 92 // if (cookie.getMaxAge() >= 0) { 93 // sb.append(";Max-Age=").append(cookie.getMaxAge()); 94 // } 95 96 // string path = VerifyUtils.isEmpty(cookie.getPath()) ? "/" : cookie.getPath(); 97 // sb.append(";Path=").append(path); 98 99 // if (cookie.getSecure()) { 100 // sb.append(";Secure"); 101 // } 102 103 // sb.append(";Version=").append(cookie.getVersion()); 104 105 // return sb.toString(); 106 // } 107 // } 108 }